#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright 2013 Antoine Drouin (poinix@gmail.com)
#
# This file is part of PAT.
#
#    PAT is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    PAT is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with PAT.  If not, see <http://www.gnu.org/licenses/>.
#

"""
 
"""

import numpy as np
import matplotlib.pyplot as plt
import control.matlab

import pat.vehicles.fixed_wing.dynamic_model_longitudinal as dm


np.set_printoptions(precision=2, suppress=True, linewidth=160)

model = dm.DynamicModel()
Xe, Ue = model.trim()
print "Xe {:s}\nUe {:s}".format(Xe, Ue)

A, B = model.jacobian(Xe, Ue)
print "A\n{:s}\nB\n{:s}".format(A, B)

w, M = np.linalg.eig(A)
print "w {:s}\nM\n{:s}".format(w, M)

Q = [0.01, 0.05,  0.001,  0.002,  0.001]
R = [0.05, 0.05]
print "LQR"
print "Q=diag(", Q, ")"
print "R=diag(", R, ")"
(K1, X, E) = control.matlab.lqr(A[1:,1:], B[1:,:], np.diag(Q), np.diag(R))

print "K {:s}".format(K1)
K = np.zeros((dm.iv_size, dm.sv_size))
K[:,1:] = K1
print "K\n{:s}".format(K)

Acl = A - np.dot(B, K)
w, M = np.linalg.eig(Acl)
print "w {:s}\nM\n{:s}".format(w, M)

dt = 0.01
time = np.arange(0., 15., dt)
X0 = np.array(Xe)
X0[dm.sv_z] -= 10
X0[dm.sv_va] += 2

X = np.zeros((len(time), dm.sv_size))
X[0] = model.reset(X0)
U = np.zeros((len(time), dm.iv_size))

for i in range(1, len(time)):
    U[i-1] = Ue - np.dot(K, X[i-1]-Xe)
    X[i] = model.run(dt, U[i-1])

model.plot_trajectory(time, X)
plt.show()
